const express = require('express')
const mysql = require('mysql')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended:true}))
//判断请求体格式是不是json格式，如果是的话会调用JSON.parse方法把请求体字符串转成对象
app.use(bodyParser.json())
const connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database:'musicmsg'
})
connection.connect()
var i = 0

app.get('/allNumber', (req, res) => { 
    const number = `select count(musicId) from musicMsg`
    connection.query(number, (err, data) => { 
        // console.log(data)
        res.send(data)
    })
})

app.post('/totop', (request, response) => {
    let msg = request.body
    // console.log(msg)
    for (var item in msg) {
        msg = item
    }
    // console.log(msg)
    let i = (msg - 1) * 15
    // console.log(i)
    // console.log(i)
    const sql = `select * from musicMsg limit ${i},15`
    connection.query(sql, (err, data) => {
        try {
            response.send(data)
        } catch{ 
            console.log(err)
        }    
    })
})
app.post('/Detail', (request, response) => {
    let msg = request.body
    // console.log(msg)
    for (var item in msg) {
        msg = item
    }
    const sql = `select * from musicMsg where musicId = ${msg}`
    connection.query(sql, (err, data, fired) => {
        try {
            response.send(data)
        } catch{ 
            console.log(err)
        }
    })
})
app.post('/player', (request, response) => { 
    let msg = request.body
    // console.log(msg)
    for (var item in msg) {
        msg = item
    }
    const sql = `select * from musicMsg where musicId = ${msg}`
    connection.query(sql, (err, data, fired) => {
        try {
            response.send(data)
        } catch{ 
            console.log(err)
        }
    })
})

app.listen(666, () => {
    console.log('Server is running on port 666')
})